using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using C3.Directory.Services;
using C3.Directory.Web.Filters;
using CSI.Directory.Core.Model;
using CSI.Directory.Core.Services;
using CSI.Directory.Web.Filters;
using StructureMap;


namespace CSI.Directory.Web.Controllers
{
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    [ValidateInput(false)]
    [RestrictedAction(new[] { "admin" },"/Login/Management")]
    public class ManagementController : BaseController
    {
        public IManagerService ManagerService
        {
            get
            {
                return ObjectFactory.GetInstance<IManagerService>();
            }
        }

        public ManagementController()
        {
            ValidateRequest = false;
        }
        public void Clear()
        {
            ManagerService.ClearCache();
        }


        public ActionResult Index()
        {
            var users = UserService.GetAllUsers().Where(t => t.Roles == "user" && t.Package > 0).ToList();
            ViewData["Expiring"] = users.Where(t => t.CreateDate.AddMonths(5) < DateTime.Now && t.CreateDate.AddMonths(6) > DateTime.Now).ToList();
            ViewData["Expired"] = users.Where(t => t.CreateDate.AddMonths(6) < DateTime.Now).ToList();
            return View();
        }

        public ActionResult AddCategory()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult AddCategory(string name, int parent, string alias)
        {
            return Json(DirectoryService.AddCategory(name, parent, alias));
        }

        public ActionResult DeleteCategory()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteCategory(int id)
        {
            return Json(DirectoryService.DeleteCategory(id));
        }


        public ActionResult AddAdmin()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult AddAdmin(string firstname, string lastname, string password, string email)
        {
            var t = new TransactionResult() { Successful = false };
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
                return Json(t); //RedirectToRoute("Controller", new { controller = "Oops" });
            t = UserService.RegisterUser(firstname, lastname, password, email, "admin");
            return Json(t);
        }

        public ActionResult Categories()
        {
            ViewData["Categories"] = DirectoryService.GetAllCategories();
            return View("ManageCategories");
        }
        //public ActionResult Features()
        //{
        //    var categories = DirectoryService.GetAllCategories();
        //    var listings = DirectoryService.GetAllListings();
        //    //foreach (var c in categories)
        //    //{
        //    //    foreach(var l in DirectoryService.GetListingsByCategory(c.Id))
        //    //    {
        //    //        listings.Add(l);
        //    //    }
        //    //}
        //    var feat = DirectoryService.GetFeaturedListingCategories();

        //    //var featListing = from l in listings join f in feat on l.Id equals f.Listing select l;
        //    //var featListing = from f in feat join l in listings on f.Listing equals l.Id select l;
        //    //foreach (var list in featListing)
        //    //{
        //    //    var c = feat.Where(t => t.Listing == list.Id).ToList();
        //    //    list.Categories = c;
        //    //}

        //    var featListing = new List<Listing>();
        //    foreach (var f in feat)
        //    {
        //        var l = listings.SingleOrDefault(t => t.Id == f.Listing);
        //        if (l == null) continue;
        //        var c = feat.Where(t => t.Listing == f.Listing).ToList();
        //        l.Categories = c;
        //        if (!featListing.Contains(l))
        //            featListing.Add(l);
        //    }


        //    ViewData["FeaturedListings"] = featListing.OrderBy(t => t.Name).ToList();
        //    ViewData["Listings"] = listings;
        //    ViewData["Categories"] = categories;
        //    return View("ManageFeatures");
        //}

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditListing(int id, string contact, string title, string email, string url, string phone, string address, string address2,
                                          string city, string state, string zipcode, string description, string keywords)
        {

            var t = DirectoryService.EditListing(id, contact, title, email, url, phone,
                                                 address, address2, city, state, zipcode, description, keywords);
            return Json(t);

        }
       
        public ActionResult EditListing(int id)
        {
            ViewData["Listing"] = DirectoryService.GetListingById(id);
            return View();
        }
        public ActionResult EditAssociations(int id)
        {
            var listing = DirectoryService.GetListingById(id);
            ViewData["ListingCategories"] = DirectoryService.GetListingCategoriesByListingId(listing.Id);
            ViewData["ListingCounties"] = DirectoryService.GetListingCountiesByListingId(listing.Id);
            ViewData["Categories"] = DirectoryService.GetAllCategories();
            ViewData["Counties"] = DirectoryService.GetAllCounties();
            ViewData["Package"] = UserService.GetUserById(listing.UserId).Package;
            ViewData["Listing"] = listing;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditAssociations(int id, string category0, string category1, string category2,
            string category3, string category4, string category5, string category6,
            string category7, string category8, string category9, string category10, 
            string county0, string county1, string county2, string county3, string county4)
        {

           return Json(DirectoryService.EditAssociations(id, category0, category1, category2,
                                                      category3, category4, category5, category6, category7, category8, category9, category10, county0, county1, county2,
                                                      county3, county4));
                       
        }
        public ActionResult ShowListings()
        {
            ViewData["Listings"] = DirectoryService.GetAllListings().OrderByDescending(t => t.CreateDate).ToList();
            return View();
        }

       

        [AcceptVerbs(HttpVerbs.Post)]
        [JsonFilter(Param = "listing", JsonDataType = typeof(ListingCategory))]
        public JsonResult AddFeature(ListingCategory listing)
        {
            var t = new TransactionResult();
            if (listing == null)
            {
                t.Exception = "Null or empty listing category";
                t.Successful = false;
                return Json(t);

            }
            listing.Feature = true;
            t = DirectoryService.FeatureListing(listing);
            return Json(t);
        }

        

        [AcceptVerbs(HttpVerbs.Post)]
        [JsonFilter(Param = "listing", JsonDataType = typeof(ListingCategory))]
        public JsonResult RemoveFeature(ListingCategory listing)
        {
            var t = new TransactionResult();
            if (listing == null)
            {
                t.Exception = "Null or empty listing";
                t.Successful = false;
                return Json(t);
            }

            t = DirectoryService.RemoveFeature(listing);
            return Json(t);
        }

        
        #region Users
        public ActionResult AllManagers()
        {
            ViewData["Users"] = ManagerService.GetAllContentManagers();
            return View();
        }
        public ActionResult ManageUser(int id)
        {
            return View(UserService.GetUserById(id));
        }
        public ActionResult NewManager()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RoleUser(int id, string role)
        {
            var u = UserService.GetUserById(id);
            u.Roles = role;
            var t = ManagerService.RoleContentManager(u);
            return t.Successful ? RedirectToAction("AllManagers", "Management") : RedirectToAction("Error", "Error", t);
        }
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult NewUser(string fullname, string username, string password, string role)
        //{
        //    var u = new User()
        //                {
        //                    FullName = fullname,
        //                    Name = username,
        //                    Roles = role,
        //                    Password = password,
        //                    CreateDate = DateTime.Now,
        //                    ModifiedDate = DateTime.Now

        //                };
        //    u.Password = UserService.SaltAndHashPassword(u);
        //    var t = ManagerService.CreateContentManager(u);
        //    return t.Successful ? RedirectToAction("AllManagers", "Management") : RedirectToAction("Error", "Error", t);
        //}
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteUser(int id)
        {

            var t = ManagerService.DeleteContentManager(UserService.GetUserById(id));
            return t.Successful ? RedirectToAction("AllManagers", "Management") : RedirectToAction("Error", "Error", t);
        }
        #endregion

        #region Articles


        public ActionResult AddArticle()
        {
            ViewData["Menus"] = DirectoryService.GetAllMenus();
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult AddArticle(string name, string body, string menuid, string featured, string desc, string keywords)
        {

            return Json(DirectoryService.AddArticle(name, body, menuid, featured, desc, keywords));

        }


        public ActionResult EditArticle(int id)
        {
            ViewData["Menus"] = DirectoryService.GetAllMenus();
            ViewData["Article"] = DirectoryService.GetArticlesById(id);

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditArticle(int id, string name, string body, string menuid, string featured, string desc, string keywords)
        {

            return Json(DirectoryService.EditArticle(id, name, body, menuid, featured, desc, keywords));



        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteArticle(int id)
        {
            var t = new TransactionResult();
            if (id == 0)
            {
                t.Exception = "Null or empty article";
                t.Successful = false;
                return Json(t);
            }
            t = DirectoryService.DeleteArticle(id);
            return Json(t);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteListing(int id)
        {
            var t = new TransactionResult();
            if (id == 0)
            {
                t.Exception = "Null or empty listing";
                t.Successful = false;
                return Json(t);
            }
            t = DirectoryService.DeleteListing(id);
            return Json(t);
        }


        public ActionResult ShowArticles()
        {
            ViewData["Articles"] = DirectoryService.GetAllArticles();
            return View();
        }

        public ActionResult ShowCategories()
        {
            ViewData["Categories"] = DirectoryService.GetAllCategories().OrderBy(t=>t.Name).ToList();
            return View();
        }

        public ActionResult ShowUsers()
        {
            ViewData["Users"] = UserService.GetAllUsers().OrderBy(t => t.Name).ToList();
            return View();
        }

        public ActionResult ShowArticlesByMenuId(int id)
        {
            return View(DirectoryService.GetArticlesByMenuId(id));
        }

        #endregion

        #region # Menu Items #

        public ActionResult AddMenu()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult AddMenu(string title, int order)
        {
            if (ModelState.IsValid)
            {
                //var menu ;
                //((CSI.Directory.Core.Model.Root)(objMenu)).Id
                var menu=new Menu();
                IList<Menu> MenuList = DirectoryService.GetAllMenus();
                foreach (Menu objmenu in MenuList)
                {
                    if (menu.Title == title)
                    {
                        var t = new TransactionResult();
                        t.Exception = "Menu name conflicted !";
                        t.Successful = false;
                        return Json(t);
                    }
                }
                menu.Name = title;
               // menu.Name = menu.Name.Replace(" ", "-");
                menu.Order = order;
                menu.CreateDate = DateTime.Now;
                menu.ModifiedDate = DateTime.Now;
                menu.Title = menu.Name.Replace(" ", "-");
                return Json(DirectoryService.AddMenu(menu));
            }
            else
            {
                var t = new TransactionResult();
                t.Exception = "Null or empty Menu Item";
                t.Successful = false;
                return Json(t);
                //return Json(objMenu);

            }
        }


        public ActionResult EditMenu(int id)
        {
            ViewData["menu"] = DirectoryService.GetMenusById(id);
            return View();
        }

        public ActionResult EditUser(int id)
        {
            ViewData["User"] = UserService.GetUserById(id);
            ViewData["Listings"] = DirectoryService.GetListingsByUserId(id);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditMenu(string title, int order,int id)
        {
            var menu = new Menu();
           // menu.Id=id;
            ViewData["menu"] = DirectoryService.GetMenusById(id);
            menu.Id = id;
            menu.Name = title;
            menu.Title = title.Replace(" ", "-");
            menu.Order = order;
            menu.CreateDate = ((CSI.Directory.Core.Model.Base)(ViewData["menu"])).CreateDate;
            menu.ModifiedDate = DateTime.Now;
            return Json(DirectoryService.EditMenu(menu));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditUser(int id, string password)
        {
           return Json(UserService.ChangePassword(id, password));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult RenewUser(int id, string renewal)
        {
            var t = UserService.RenewUser(id, renewal);
            t.Successful &= DirectoryService.ActivateListingForUser(id).Successful;
            return Json(t);
        }

        public ActionResult RenewUser(int id)
        {
            ViewData["User"] = UserService.GetUserById(id);

            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteMenu(int id)
        {
            var t = new TransactionResult();
            if (id == 0)
            {
                t.Exception = "Null or empty article";
                t.Successful = false;
                return Json(t);
            }
            t = DirectoryService.DeleteMenu(id);
            return Json(t);
        }


        public ActionResult ShowMenu()
        {
           // return View();
            ViewData["menu"] = DirectoryService.GetAllMenus();
            return View();
          
        }

        #endregion

        #region # Manage listing,Categories #
        public ActionResult ManageDirectory()
        {
            ViewData["Listings"] = DirectoryService.GetAllListings();
            return View();
        }
        public ActionResult ManageCategories()
        {
            ViewData["Categories"] = DirectoryService.GetAllCategories();
            return View();
        }
        public ActionResult ManageFeatures()
        {
            //ViewData["Categories"] = DirectoryService.GetAllCategories();
            ViewData["Listings"] = DirectoryService.GetAllListings();
            ViewData["Categories"] = DirectoryService.GetAllCategories();
            ViewData["FeaturedListings"] = DirectoryService.GetFeaturedListings();
            return View();
        }
        #endregion

    }
}